<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-row>
        <el-form-item label="活动标题" prop="lotteryTitle">
          <el-input v-model="queryParams.lotteryTitle" placeholder="请输入活动标题" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="活动状态" prop="lotteryStatus">
          <el-select v-model="queryParams.lotteryStatus" placeholder="请选择活动状态" clearable size="small">
            <el-option v-for="dict in lotteryStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: 22px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button style="color:#fff;" type="primary" size="mini" @click="handleAdd"
          v-hasPermi="['activity:lottery:add']">新建活动</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['activity:lottery:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['activity:lottery:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['activity:lottery:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

<div class="divTable">
    <el-table border v-loading="loading" :data="lotteryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="封面图" align="center" prop="lotteryImg" :show-overflow-tooltip="true" width="80">
        <template slot-scope="scope">
          <el-image v-if="scope.row.lotteryImg != null && scope.row.lotteryImg != '' " slot="reference"
            :src="scope.row.lotteryImg" class="image-rows" :preview-src-list="[scope.row.lotteryImg]"></el-image>
        </template>
      </el-table-column>
      <!-- <el-table-column label="描述图片" align="center" prop="lotteryRemarkImg" :show-overflow-tooltip="true" width="80">
        <template slot-scope="scope">
          <el-image v-if="scope.row.lotteryRemarkImg != null && scope.row.lotteryRemarkImg != '' " slot="reference"
            :src="scope.row.lotteryRemarkImg" class="image-rows" :preview-src-list="[scope.row.lotteryRemarkImg]"></el-image>
        </template>
      </el-table-column> -->
      <el-table-column label="活动标题" align="left" prop="lotteryTitle" :show-overflow-tooltip="true" width="150" >
        <template slot-scope="scope">
      		<el-button size="mini" type="text" @click="handleShowDetail(scope.row)">{{ scope.row.lotteryTitle }}
      		</el-button>
      	</template>
      </el-table-column>
      <!-- <el-table-column label="轮盘数量" align="center" prop="lotteryNumber" :show-overflow-tooltip="true" /> -->
      <el-table-column label="抽奖周期" align="center" prop="lotteryFrequency" :formatter="lotteryFrequencyFormat" />
      <el-table-column label="抽奖次数" align="center" prop="lotteryLimit" :show-overflow-tooltip="true" />
      <el-table-column label="消耗积分" align="center" prop="lotteryFate" :show-overflow-tooltip="true" />
      <el-table-column label="活动开始时间" align="center" prop="lotteryStarttime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lotteryStarttime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="lotteryEndtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lotteryEndtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动描述" align="center" prop="lotteryText" :show-overflow-tooltip="true" />
      <el-table-column label="活动状态" align="center" prop="lotteryStatus" :formatter="lotteryStatusFormat" >
      <template slot-scope="scope">
      		<el-switch v-model="scope.row.lotteryStatus" active-value="1" inactive-value="0"
      			@change="handleStatusChange(scope.row)"></el-switch>
      	</template>
      </el-table-column>
      <el-table-column label="修改人名称" align="center" prop="lotteryUpdatename" width="130" :show-overflow-tooltip="true" />
      <el-table-column label="修改时间" align="center" prop="lotteryUpdatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lotteryUpdatetime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="130">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleShowDetail(scope.row)"
            v-hasPermi="['activity:lottery:query']">查看</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['activity:lottery:edit']">修改</el-button>
          <el-button v-if="scope.row.lotteryStatus == '0'" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['activity:lottery:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
</div>

    <!-- 添加或修改抽奖活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动封面图" prop="lotteryImg">
          <imageUpload v-model="form.lotteryImg" />
        </el-form-item>
        <el-form-item label="活动标题" prop="lotteryTitle">
          <el-input v-model="form.lotteryTitle" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="轮盘数量" prop="lotteryNumber">
          <el-input v-model="form.lotteryNumber" placeholder="请输入轮盘数量" oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="抽奖次数" prop="lotteryLimit">
          <el-input v-model="form.lotteryLimit" placeholder="请输入抽奖次数" oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="消耗积分" prop="lotteryFate">
          <el-input v-model="form.lotteryFate" placeholder="请输入消耗积分" oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="活动描述" prop="lotteryText">
          <el-input v-model="form.lotteryText" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="描述图片" >
          <imageUpload v-model="form.lotteryRemarkImg" />
        </el-form-item>
        <el-form-item label="抽奖周期" prop="lotteryFrequency">
          <el-select v-model="form.lotteryFrequency" placeholder="请选择抽奖周期">
            <el-option v-for="dict in lotteryFrequencyOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示中奖名单" prop="lotteryShow">
          <el-select v-model="form.lotteryShow" placeholder="请选择">
            <el-option v-for="dict in lotteryShowOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动开始时间" prop="lotteryStarttime">
          <el-date-picker clearable size="small" v-model="form.lotteryStarttime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="lotteryEndtime">
          <el-date-picker clearable size="small" v-model="form.lotteryEndtime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择活动结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看抽奖活动对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="1000px" append-to-body>
      <lotteryView v-if="showData" :lotteryVo="showData" ></lotteryView>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listLottery,
    getLottery,
    delLottery,
    addLottery,
    updateLottery,
    updateStatus
  } from "@/api/activity/lottery";

import lotteryView from './view';
import ImageUpload from '@/components/ImageUpload';

  export default {
    name: "Lottery",
    components: {
      lotteryView,
      ImageUpload,
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 抽奖活动表格数据
        lotteryList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        viewOpen: false,
        //查看详细数据
        showData: {},
        // 抽奖周期字典
        lotteryFrequencyOptions: [],
        // 活动状态字典
        lotteryStatusOptions: [],
        //中奖名单字典
        lotteryShowOptions:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          platformUid: null,
          lotteryTitle: null,
          lotteryImg: null,
          lotteryNumber: null,
          lotteryLimit: null,
          lotteryStarttime: null,
          lotteryEndtime: null,
          lotteryFrequency: null,
          lotteryFate: null,
          lotteryRemarkImg: null,
          lotteryStatus: null,
          lotteryText: null,
          lotteryCreateuser: null,
          lotteryCreatename: null,
          lotteryCreatetime: null,
          lotteryUpdateuser: null,
          lotteryUpdatename: null,
          lotteryUpdatetime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          lotteryTitle: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryImg: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryNumber: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryLimit: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryStarttime: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryEndtime: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryFrequency: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryFate: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          lotteryShow: [
            { required: true, message: "不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("activity_lottery_frequency").then(response => {
        this.lotteryFrequencyOptions = response.data;
      });
      this.getDicts("activity_data_status").then(response => {
        this.lotteryStatusOptions = response.data;
      });
      this.getDicts("activity_lottery_show").then(response => {
        this.lotteryShowOptions = response.data;
      });
    },
    //监听路由
		watch: {
		  $route(to, from) {
			//from 从哪来
			//to //到哪去
			let path = from.path;
			console.log(path)
			if ("/luckDraw/data/" == path) {
			  //刷新页面
			  this.getList();
			} else {
			  let index = path.lastIndexOf("/");
			  if (index > -1) {
				path = path.substr(0, index);
				if ("/luckDraw/data" == path) {
				  //刷新页面
				  this.getList();
				}
			  }
			}
		  }
		},
    methods: {
      /** 查询抽奖活动列表 */
      getList() {
        this.loading = true;
        listLottery(this.queryParams).then(response => {
          this.lotteryList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 抽奖周期字典翻译
      lotteryFrequencyFormat(row, column) {
        return this.selectDictLabel(this.lotteryFrequencyOptions, row.lotteryFrequency);
      },
      // 活动状态字典翻译
      lotteryStatusFormat(row, column) {
        return this.selectDictLabel(this.lotteryStatusOptions, row.lotteryStatus);
      },
      // 中奖名单字典翻译
      lotteryShowFormat(row, column) {
        return this.selectDictLabel(this.lotteryShowOptions, row.lotteryShow);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          lotteryUid: null,
          platformUid: null,
          lotteryTitle: null,
          lotteryImg: null,
          lotteryNumber: null,
          lotteryLimit: null,
          lotteryStarttime: null,
          lotteryEndtime: null,
          lotteryFrequency: null,
          lotteryFate: null,
          lotteryRemarkImg: null,
          lotteryStatus: null,
          lotteryText: null,
          lotteryCreateuser: null,
          lotteryCreatename: null,
          lotteryCreatetime: null,
          lotteryUpdateuser: null,
          lotteryUpdatename: null,
          lotteryUpdatetime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.lotteryUid)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        this.names = selection.map(item => item.lotteryTitle);
        //用于禁用删除
        if (this.multiple == false) {
          for (var i = 0; i < selection.length; i++) {
            var element = selection[i];
            if ("1" === element.lotteryStatus) {
              this.multiple = true;
              break;
            }
          }
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.$router.push("/luckDraw/data/")
      },
      /** 查看详情按钮操作 **/
      handleShowDetail(row) {
        this.showData = null;
        const lotteryUid = row.lotteryUid;
        this.$router.push("/luckDraw/view/" + lotteryUid)
        // getLottery(lotteryUid).then(response => {
        //   this.showData = response.data;
        //   this.viewOpen = true;
        //   this.viewTitle = "订单详情";
        // });
      },
      handCloseDetail() {
        this.viewOpen = false
        this.showData = null
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        const lotteryUid = row.lotteryUid || this.ids
        // getLottery(lotteryUid).then(response => {
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "修改抽奖活动";
        //   console.log(this.form);
        // });
        this.$router.push("/luckDraw/data/" + lotteryUid)
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.lotteryUid != null) {
              updateLottery(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addLottery(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      // 状态修改
      handleStatusChange(row) {
      	let text = row.lotteryStatus === "0" ? "下架" : "上架";
      	this.$confirm('确定要把奖品名称为"' + row.lotteryTitle + '",设为' + text + '吗？', "警告", {
      		confirmButtonText: "确定",
      		cancelButtonText: "取消",
      		type: "warning"
      	}).then(function() {
      		return updateStatus(row.lotteryUid, row.lotteryStatus);
      	}).then(() => {
      		this.msgSuccess("操作成功");
      		this.getList();
      	}).catch(function() {
      		row.lotteryStatus = row.lotteryStatus === "0" ? "1" : "0";
      	});
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const lotteryUids = row.lotteryUid || this.ids;
        const names = row.lotteryTitle || this.names;
        this.$confirm('是否确认删除抽奖活动名称为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLottery(lotteryUids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('activity/lottery/export', {
          ...this.queryParams
        }, `activity_lottery.xlsx`)
      }
    }
  };
</script>
